package br.com.leilao.filter;


import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.leilao.managebean.LoginMB;
import br.com.leilao.model.Usuario;


public class Filter implements javax.servlet.Filter{


	FilterConfig fc;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest  req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
		String url = req.getRequestURL().toString();
		Usuario usuario;
		
		
		try{
			LoginMB loginMB =(LoginMB) req.getSession().getAttribute("loginMB"); 
			usuario = loginMB.getUsuario();
		}catch (Exception e) {
		 usuario=null;	
		}
		if((usuario == null) && !url.contains("index.jsp") && !url.contains("login.jsf")){
			res.sendRedirect("../index.jsf");
		}else{
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.fc=filterConfig;
	}

}